<?php

namespace Common\Lib;

use Think\Controller;

/**
 * 短信接口
 */
class SMSLib extends Controller
{

    /**
     * 发送手机短信
     * @param $mobiles 手机号，多个手机号用英文逗号（,）分割
     * @param $content 内容
     * @return array
     */
    public function sendSMS($mobiles, $content)
    {
        $sms_config = C('SMS');
        error_log(print_r($sms_config,1));
        $accesstoken = $this->getAccessToken();
        $time = date('Y-m-d H:i:s');
        $data = array(
            'appid' => $sms_config['APPID'],
            'token' => $accesstoken,
            'timestamp' =>  strtotime($time),
            'content' => $content,
            'phone' => $mobiles
        );
        error_log(print_r($data,1));
        $result = $this->http_request($sms_config['URL'] . 'api/v1.1/sendsms', $data);
        error_log(print_r($result,1));
        return json_decode($result, true);
    }


    public function getAccessToken()
    {
        //$accesstoken = RedisHandle::getSMSAccesstoken();
        //if ($accesstoken) {
        //    return $accesstoken;
        //}

        $sms_config = C('SMS');
        $data = array(
            'appid' => $sms_config['APPID'],
            'secret' => $sms_config['APPSECRET']
        );
        $result = $this->http_request($sms_config['URL'] . 'api/access_token', $data);

        $tokeninfo = json_decode($result, true);
        RedisHandle::saveSMSAccesstoken($tokeninfo['data']);
        return $tokeninfo['data'];
    }


    /**
     * CURL封装
     * @param  string $url 路由
     * @param  array $data 请求数据
     * @return json   $res   返回值
     */
    public function http_request($url, $data = null)
    {
        // curl 初始化
        $curl = curl_init();
        // curl 请求头设置
        $headers = array();
        $headers[] = "Accept:application/json";
        $headers[] = "Content-Type:application/x-www-form-urlencoded";
        $headers[] = "charset=utf-8";
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        // curl 设置
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);  // 查看ssl 证书节点
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);  // 查看ssl 证书主机
        // 判断有没有 data 如果有data 我们就是post
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        // 执行
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;
    }
}






